//
//  StatusPictureView.swift
//  Weibo
//
//  Created by apple on 15/12/12.
//  Copyright © 2015年 idcast. All rights reserved.
//

import UIKit
import SDWebImage
//照片之间的距离
private let StatusPictureViewItemMargin: CGFloat = 8
//可重用cell的表示符号
private let StatusPictureCellId = "StatusPictureCellId"

class StatusPictureView: UICollectionView {
    var viewModel: StatusViewModel? {
        didSet{
        //自动计算大小
            sizeToFit()
            //刷新数据
            reloadData()
        }
    }
    
    
    override func sizeThatFits(size: CGSize) -> CGSize {
        return calcViewSize()
    }
    
    //MARK : 构造函数
    init() {
        let layout = UICollectionViewFlowLayout()
        //设置间距 默认是 itemsize 50 * 50
        layout.minimumInteritemSpacing = StatusPictureViewItemMargin
        layout.minimumLineSpacing = StatusPictureViewItemMargin
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        backgroundColor = UIColor(white: 0.95, alpha: 1.0)
        
        //设置数据源
        dataSource = self
        
        //设置代理 
        delegate = self
        //注册可重用的cell
        registerClass(StatusPictureViewCell.self, forCellWithReuseIdentifier: StatusPictureCellId)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

//MARK 数据源方法
extension StatusPictureView: UICollectionViewDataSource, UICollectionViewDelegate {
    ///选中照片
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        print("点击照片\(indexPath) \(viewModel?.thumbnailUrks)")
        
        /**
        1 明确问题 传递什么数据 当前URL的数组/ 当前用户选中的索引
        2 任何才能传递 利用通知
        3 通知 名字（通知监听中心） object：发送通知的同时传递对象(单值) userinfo 传递多值的时候使用的数据字典 -> key
        */
        

        //发送通知
        NSNotificationCenter.defaultCenter().postNotificationName(WBStatusSelectedPhotoNotification,
            object: self,
            userInfo: [WBStatusSelectedPhotoIndexPathKey: indexPath, WBStatusSelectedPhotoURLsKey: viewModel!.thumbnailUrks!])
    }

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return viewModel?.thumbnailUrks?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(StatusPictureCellId, forIndexPath: indexPath) as! StatusPictureViewCell
//        cell.backgroundColor = UIColor.redColor()
        cell.imageURL = viewModel!.thumbnailUrks![indexPath.item]
        return cell
    }
}

//MARK: 计算试图的大小
extension StatusPictureView {

    //计算试图大小
    private func calcViewSize() -> CGSize {
    
        //1 准备 
        //每行照片的数量
        let rowCount: CGFloat = 3
        
        //最大宽度
        let maxWidth = UIScreen.mainScreen().bounds.width - 2 * StatusCellMargin
        let itemWidth = (maxWidth - 2 * StatusPictureViewItemMargin) / rowCount
        
        //2 设置layout 的 itemsize
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        
        //3 获取图片的数量
        let count = viewModel?.thumbnailUrks?.count ?? 0
        
        //计算开始
        //1 没有图片
        if count == 0 {
        
            return CGSizeZero
        }
        
        //2 一张图片
        if count == 1 {
        
            ///临时指定的大小
            var size = CGSize(width: 150, height: 120)
            
            //利用SDWebimage来检查本地缓存图像。  key就是url完整字符串
            if let key = viewModel?.thumbnailUrks?.first?.absoluteString{
            
                if let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key) {
                
                    size = image.size
                }
            }
            //过窄处理
            size.width = size.width < 40 ? 40 : size.width
            //过宽处理
            if size.width > 300 {
            
                let w: CGFloat = 300
                let h = size.width * w / size.width
                size = CGSize(width: w, height: h)
            }
            
            //内部图片的大小
            layout.itemSize = size
            
            //p配置试图的大小
            return size
        }
        
        //3 四张图片的 2 * 2 的大小
        if count == 4 {
        
            let w = 2 * itemWidth + StatusPictureViewItemMargin
            return CGSize(width: w, height: w)
            
        }
        
        //4 其他图片
        let row = CGFloat((count - 1) / Int(rowCount) + 1)
        let h = row * itemWidth + (row - 1) * StatusPictureViewItemMargin
        let w = rowCount * itemWidth + (rowCount - 1) * StatusPictureViewItemMargin
        
        return CGSize(width: w, height: h)
        
    }
}
//MARK: 配图cell
private class StatusPictureViewCell: UICollectionViewCell{
    var imageURL: NSURL? {
    
        didSet{
        
            iconView.sd_setImageWithURL(imageURL,
                placeholderImage: nil,//调用OC 的框架时 可选必选项不严格
                options: [SDWebImageOptions.RetryFailed,SDWebImageOptions.RefreshCached])
            //SD超时时长为15s 一旦超时就会计入黑命单           如果url不变 图像变
        }
    }
    //构造方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupUI() {
    
        //1 添加控件
        contentView.addSubview(iconView)
        
        // 2. 设置布局 - 提示因为 cell 会变化，另外，不同的 cell 大小可能不一样
        iconView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
    }
    //懒加载控件
    private lazy var iconView: UIImageView = {
    
        let iv = UIImageView()
        //设置填充模式
        iv.contentMode = UIViewContentMode.ScaleAspectFill
        //需要剪切图片
        iv.clipsToBounds = true
        
        return iv
    }()
}
